package com.ruogu.codegeneration.annotation;

import com.ruogu.codegeneration.exception.BusinessException;
import com.ruogu.codegeneration.exception.ErrorCode;
import com.ruogu.codegeneration.model.entity.User;
import com.ruogu.codegeneration.model.enums.UserRoleEnum;
import com.ruogu.codegeneration.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * @author ruogu
 */
@Aspect
@Component
public class AuthInterceptor {

    @Resource
    private UserService userService;

    /**
     * 执行拦截
     *
     * @param joinPoint 切入点
     * @param authCheck 权限校验注解
     */
    @Around("@annotation(authCheck)")
    public Object doInterceptor(ProceedingJoinPoint joinPoint, AuthCheck authCheck) throws Throwable {
        String mustRole = authCheck.mustRole();
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();

        // 当前登录用户
        User loginUser = userService.getLoginUser(request);
        // 不需要权限，放行
        if (mustRole == null || mustRole.isEmpty()) {
            return joinPoint.proceed();
        }

        UserRoleEnum mustRoleEnum = UserRoleEnum.getEnumByValue(mustRole);
        if (mustRoleEnum == null) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无效的权限要求");
        }

        // 用户未登录或无法获取角色信息
        if (loginUser == null) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }

        String userRoleStr = loginUser.getUserRole();
        UserRoleEnum userRoleEnum = UserRoleEnum.getEnumByValue(userRoleStr);
        if (userRoleEnum == null) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "用户角色无效");
        }

        // 权限不足，拒绝访问
        if (!hasPermission(userRoleEnum, mustRoleEnum)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }

        // 通过权限校验，放行
        return joinPoint.proceed();
    }

    /**
     * 判断用户是否具有指定权限
     *
     * @param userRoleEnum 用户角色
     * @param mustRoleEnum 所需角色
     * @return 是否有权限
     */
    private boolean hasPermission(UserRoleEnum userRoleEnum, UserRoleEnum mustRoleEnum) {
        // 管理员拥有所有权限
        if (UserRoleEnum.ADMIN.equals(userRoleEnum)) {
            return true;
        }
        // 其他情况精确匹配
        return userRoleEnum.equals(mustRoleEnum);
    }

}
